package com.itheima.sh.service;

import com.itheima.sh.dao.UserMapper;
import com.itheima.sh.pojo.User;
import com.itheima.sh.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

public class UserServiceImpl {
    //1.定义登录方法接收web层传递的User对象
    public User login(User user) {
        //2. 在登录方法体中获取myabtis会话对象
        SqlSession sqlSession = SqlSessionUtil.getSqlSession(false);
        //3. 使用会话对象调用方法获取接口代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4. 使用接口代理对象调用接口登录方法，返回User对象
        User u = mapper.login(user);
        //5. 释放资源
        sqlSession.close();
        //6. 将查询的User对象返回给web层
        return u;
    }

    //定义注册方法接收web层传递的User对象
    public boolean register(User user) {
        //在注册方法体中获取myabtis会话对象
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();//自动提交事务
        //使用会话对象调用方法获取接口代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User u = mapper.queryUserByUsername(user.getUsername());
            if (u==null){
                mapper.register(user);
                sqlSession.close();
                return true;
            }else{
                sqlSession.close();
                return false;
            }
    }
}
